*
* Purpose:
*	Prepare data for welfare analysis
*

* Prepare contracts (temp)
use "${raw_data_contracts_${year}}", clear
	keep if eljaras == 1
	do "${helpers_dir}/dropErroneousContracts${year}.do"
save "${data_contracts_${year}}", replace


* Add priority scores (from applications w prioirty scores data) and priority-score cutoffs (contracts data) to core applications data
use "${raw_data_applications_${year}}", clear
	keep if eljaras == 1
	merge n:1 karkod szaknev szint munkarend fin_form using "${data_contracts_${year}}"
	drop if _m == 2
	drop _m

	do "${helpers_dir}/tidyVariableForWelfareAnalysis.do"

	merge 1:1 id rank using "${data_applications_ps_${year}}"
	drop if _m == 2
	drop _m
	
	keep applicant_id rank program_id contract_id state_funded admitted priority_score priority_score_cutoff id
	
	* Admitted, priority score is below priority-score cutoff
	do "${helpers_dir}/addAdmittedBelowPSCutoff.do"

	* Rejected, priority score is above priority-score cutoff
	do "${helpers_dir}/addHasJustifiedEnvy.do"

	
	preserve 
		* Remove erroneous applications
		drop if admitted_below_ps_cutoff == 1 | has_justified_envy == 1
		drop admitted_below_ps_cutoff has_justified_envy
		
		drop if priority_score == 0
		

		* Add capacities
		do "${helpers_dir}/addCapacity.do"
		
		* sort applicant_id rank
		* bys applicant_id: gen rank_new = _n
		* drop rank
		* rename rank_new rank
		
		export delimited applicant_id ///
					rank ///
					priority_score ///
					contract_id ///
					capacity ///
					state_funded ///
					program_id ///
					admitted ///
					using "${csv_welfare_analysis_no_err_${year}}", nolabel replace
	
		compress
		save "${welfare_analysis_no_err_${year}}", replace
	
	
	restore
	drop rejected
		
	compress
	
save "${data_for_welfare_analysis_${year}}", replace
	